package com.unience.ec2.eclipse.view;

import java.util.ArrayList;
import java.util.List;

import org.eclipse.ui.part.ViewPart;
import org.eclipse.jface.resource.ImageDescriptor;
import org.eclipse.swt.events.SelectionEvent;
import org.eclipse.swt.events.SelectionListener;
import org.eclipse.swt.layout.GridLayout;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.MessageBox;
import org.eclipse.swt.widgets.Table;
import org.eclipse.swt.widgets.TableColumn;
import org.eclipse.swt.widgets.TableItem;
import org.eclipse.swt.widgets.ToolBar;
import org.eclipse.swt.widgets.ToolItem;
import org.eclipse.swt.SWT;
import org.eclipse.swt.events.SelectionAdapter;
import org.eclipse.swt.layout.FormData;
import org.eclipse.swt.layout.GridData;
import org.jfree.experimental.swt.SWTUtils;

import com.unience.ec2.eclipse.config.Config;
import com.unience.ec2.eclipse.config.UtilSWT;
import com.unience.ec2.eclipse.dialog.GrantAccessDialog;
import com.unience.ec2.eclipse.dialog.NewAccountDialog;
import com.unience.ec2.eclipse.dialog.NewSecurityGroupDialog;
import com.xerox.amazonws.ec2.EC2Exception;
import com.xerox.amazonws.ec2.GroupDescription;
import com.xerox.amazonws.ec2.Jec2;
import com.xerox.amazonws.ec2.GroupDescription.IpPermission;
import com.xerox.amazonws.typica.jaxb.GroupSetType;



/**
 * This code was edited or generated using CloudGarden's Jigloo SWT/Swing GUI
 * Builder, which is free for non-commercial use. If Jigloo is being used
 * commercially (ie, by a corporation, company or business for any purpose
 * whatever) then you should purchase a license for each developer using Jigloo.
 * Please visit www.cloudgarden.com for details. Use of Jigloo implies
 * acceptance of these licensing terms. A COMMERCIAL LICENSE HAS NOT BEEN
 * PURCHASED FOR THIS MACHINE, SO JIGLOO OR THIS CODE CANNOT BE USED LEGALLY FOR
 * ANY CORPORATE OR COMMERCIAL PURPOSE.
 */
public class SecurityGroupViewPart extends ViewPart implements SelectionListener{
    public static final String ID_VIEW =
        "com.unience.ec2.eclipse.view.SecurityGroupViewPart"; //$NON-NLS-1$
        private Table tableSecGroupConfig;
        private ToolItem toolItem2;
        private ToolBar toolBarSecGroupConfig;
        private Table tableSecurityGroups;
        private ToolItem toolItem1;
        private ToolBar toolBar;
        
        Composite parent;

    Composite composite1;
    GroupDescription groupDesc;
    
    Jec2 jec2 ;
    /**
	 * 
	 */
    public SecurityGroupViewPart() {
        super();
        groupDesc = (GroupDescription)Config.getInstance().getLastSelection();
    }

    /*
	 * (non-Javadoc)
	 * 
	 * @see org.eclipse.ui.IWorkbenchPart#createPartControl(org.eclipse.swt.widgets.Composite)
	 */
    public void createPartControl(Composite parent) {
    	{
    		
    		this.parent = parent ;
    		Config config = Config.getInstance();
        	jec2 =  config.getEc2Instance().getEc2();
        	
	    	parent.setSize(1023, 634);
	    	{
	    		composite1 = new Composite(parent, SWT.NULL);
	    		GridLayout composite1Layout = new GridLayout();
	    		composite1.setLayout(composite1Layout);
	    		{
	    			toolBar = new ToolBar(composite1, SWT.NONE);
	    			{
	    				toolItem1 = new ToolItem(toolBar, SWT.NONE);	    				
	    				toolItem1.setText("Refresh");
	    				ImageDescriptor descriptor =ImageDescriptor.createFromFile(Config.class,"refresh.png" );
	    				toolItem1.setImage(descriptor.createImage());
	    				toolItem1.addSelectionListener(new SelectionAdapter() {
	    					public void widgetSelected(SelectionEvent event) {
	    						tableSecGroupConfig.removeAll();
	    						tableSecurityGroups.removeAll();
	    						loadSecurityGroups();
	    						
	    					}
	    				});
	    				
	    				toolItem1 = new ToolItem(toolBar, SWT.NONE);	    				
	    				toolItem1.setText("Add");
	    				descriptor =ImageDescriptor.createFromFile(Config.class,"action_add.png" );
	    				toolItem1.setImage(descriptor.createImage());
	    				toolItem1.addSelectionListener(new SelectionAdapter() {
	    					public void widgetSelected(SelectionEvent event) {	
	    						NewSecurityGroupDialog inst = new NewSecurityGroupDialog(UtilSWT.getShell(),
	    								SWT.NULL);

	    						inst.open();

	    						if (inst.isAccepted()) {
	    							try {
										jec2.createSecurityGroup(inst.getName(), inst.getDesc());
										tableSecGroupConfig.removeAll();
			    						tableSecurityGroups.removeAll();
			    						loadSecurityGroups();
									} catch (EC2Exception e) {
										// TODO Auto-generated catch block
										e.printStackTrace();
									}	    						
	    						}
	    						
	    						
	    					}
	    				});
	    				
	    				toolItem1 = new ToolItem(toolBar, SWT.NONE);	    				
	    				toolItem1.setText("Delete");
	    				descriptor =ImageDescriptor.createFromFile(Config.class,"action_remove.png" );
	    				toolItem1.setImage(descriptor.createImage());
	    				toolItem1.addSelectionListener(new SelectionAdapter() {
	    					public void widgetSelected(SelectionEvent event) {	
	    						
	    						 MessageBox messageBox = new MessageBox(UtilSWT.getShell(),  SWT.ICON_WARNING| SWT.YES | SWT.NO );
	    					        
	    					        messageBox.setText("Warning");
	    					        messageBox.setMessage("Are you sure to Delete the Security Group?");
	    					        int buttonID = messageBox.open();
	    					        switch(buttonID) {
	    					          case SWT.YES:
	    					        	  TableItem[] items = tableSecurityGroups.getSelection();			
	    		    						

	    		    						for (TableItem tableItem : items) {
	    		    							
	    		    							GroupDescription groupDesc = (GroupDescription)tableItem.getData();
	    		    							
	    		    							try {
	    											jec2.deleteSecurityGroup(groupDesc.getName());
	    											tableSecGroupConfig.removeAll();
	    				    						tableSecurityGroups.removeAll();
	    				    						loadSecurityGroups();
	    										} catch (EC2Exception e) {
	    											// TODO Auto-generated catch block
	    											e.printStackTrace();
	    										}
	    		    							
	    		    							break;
	    		    						}
	    					          case SWT.NO:
	    					            // exits here ...
	    					            break;
	    					         
	    					        }
	    						
	    						
	    						
	    					}
	    				});
	    				
	    				
	    				
	    				
	    			}
	    		}
	    		{
	    			GridData tableSecurityGroupsLData = new GridData();
	    			tableSecurityGroupsLData.widthHint = 993;
	    			tableSecurityGroupsLData.heightHint = 216;
	    			tableSecurityGroups = new Table(composite1, SWT.NONE);
	    			tableSecurityGroups.setLayoutData(tableSecurityGroupsLData);
	    			
	    			TableColumn tc1 = new TableColumn(tableSecurityGroups, SWT.CENTER);
	                TableColumn tc2 = new TableColumn(tableSecurityGroups, SWT.CENTER);
	                TableColumn tc3 = new TableColumn(tableSecurityGroups, SWT.CENTER);
	                
	                tc1.setText("Owner");
	                tc2.setText("Name");
	                tc3.setText("Description");
	                
	                tc1.setWidth(180);
	                tc2.setWidth(180);
	                tc3.setWidth(180);
	                
	                tableSecurityGroups.setHeaderVisible(true);
	                tableSecurityGroups.addSelectionListener(new SelectionAdapter() {
	                	public void widgetSelected(SelectionEvent evt) {
	                		tableSecurityGroupsWidgetSelected(evt);
	                	}
	                });
	    		}
	    		{
	    			toolBarSecGroupConfig = new ToolBar(composite1, SWT.NONE);
	    			{
	    				toolItem2 = new ToolItem(toolBarSecGroupConfig, SWT.NONE);	    				  				
	    				toolItem2.setText("Grant");
	    				
	    				ImageDescriptor descriptor =ImageDescriptor.createFromFile(Config.class,"action_add.png" );
	    				toolItem2.setImage(descriptor.createImage());
	    				toolItem2.addSelectionListener(new SelectionAdapter() {
	    					public void widgetSelected(SelectionEvent event) {	
	    						
	    						GrantAccessDialog inst = new GrantAccessDialog(UtilSWT.getShell(),
	    								SWT.NULL);

	    						inst.open();

	    						if (inst.isAccepted()) {
	    							
	    							
	    						}
	    						TableItem[] items = tableSecurityGroups.getSelection();			
	    						

	    						for (TableItem tableItem : items) {
	    							
	    							GroupDescription groupDesc = (GroupDescription)tableItem.getData();
	    							
	    							
	    							break;
	    						}
	    						
	    						
	    					}
	    				});
	    				
	    				toolItem2 = new ToolItem(toolBarSecGroupConfig, SWT.NONE);
	    				toolItem2.setText("Revoke");
	    				descriptor =ImageDescriptor.createFromFile(Config.class,"action_delete.png" );
	    				toolItem2.setImage(descriptor.createImage());
	    				toolItem2.addSelectionListener(new SelectionAdapter() {
	    					public void widgetSelected(SelectionEvent event) {		
	    						
	    					}
	    				});
	    				
	    				
	    			}
	    		}
	    		{
	    			GridData tableSecGroupConfigLData = new GridData();
	    			tableSecGroupConfigLData.widthHint = 989;
	    			tableSecGroupConfigLData.heightHint = 303;
	    			tableSecGroupConfig = new Table(composite1, SWT.NONE);
	    			tableSecGroupConfig.setLayoutData(tableSecGroupConfigLData);
	    			
	    			TableColumn tc1 = new TableColumn(tableSecGroupConfig, SWT.CENTER);
	                TableColumn tc2 = new TableColumn(tableSecGroupConfig, SWT.CENTER);
	                TableColumn tc3 = new TableColumn(tableSecGroupConfig, SWT.CENTER);
	                TableColumn tc4 = new TableColumn(tableSecGroupConfig, SWT.CENTER);
	                
	                tc1.setText("Protocol");
	                tc2.setText("From Port/ICMP");
	                tc3.setText("To Port/ICMP");
	                tc4.setText("Source CIRD");
	                
	                tc1.setWidth(180);
	                tc2.setWidth(180);
	                tc3.setWidth(180);
	                tc4.setWidth(180);
	                
	                tableSecGroupConfig.setHeaderVisible(true);
	                
	                
	    		}
	    	}
    	}
    	
    	loadSecurityGroups();
    }

    /*
	 * (non-Javadoc)
	 * 
	 * @see org.eclipse.ui.IWorkbenchPart#setFocus()
	 */
    public void setFocus() {
        // TODO Auto-generated method stub
    }
    
    /**
	 * Cleans up all resources created by this ViewPart.
	 */
    public void dispose() {
        super.dispose();
    }
    
    private void loadSecurityGroups(){
    	try {
			List<GroupDescription> groups = jec2.describeSecurityGroups(new ArrayList<String>());
			for (GroupDescription groupDescription : groups) {
				
								
				TableItem item = new TableItem(tableSecurityGroups, SWT.NONE);
				item.setText(new String[] {groupDescription.getOwner(), groupDescription.getName(), groupDescription.getDescription()});
				item.setData(groupDescription);
			}
			
		} catch (EC2Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
    	
    }

	public void widgetDefaultSelected(SelectionEvent e) {
		// TODO Auto-generated method stub
		
	}

	public void widgetSelected(SelectionEvent e) {
		// TODO Auto-generated method stub
		
	}
	
	private void tableSecurityGroupsWidgetSelected(SelectionEvent evt) {
		System.out.println("tableSecurityGroups.widgetSelected, event="+evt);
		
		TableItem[] items = tableSecurityGroups.getSelection();
		
		tableSecGroupConfig.removeAll();

		for (TableItem tableItem : items) {
			
			GroupDescription groupDesc = (GroupDescription)tableItem.getData();
		
			
			
			List <IpPermission> ipPermisions = groupDesc.getPermissions();
			
			for (IpPermission ipPermission : ipPermisions) {
				TableItem item = new TableItem(tableSecGroupConfig, SWT.NONE);
				String ipFrom = Integer.toString(ipPermission.getFromPort());
				String ipTo = Integer.toString(ipPermission.getToPort());
				
				List<String> ipRanges = ipPermission.getIpRanges();
				StringBuffer ipRangesBuf = new StringBuffer();
				for (String string : ipRanges) {
					ipRangesBuf.append(string).append(" ");
				}						
				
				item.setText(new String[] {ipPermission.getProtocol(), ipFrom, ipTo, ipRangesBuf.toString() });
				item.setData(ipPermission);
			
				
			}
			
			break;
			
		}
	}
}
